package logic

import (
	"context"
	"errors"
	"user_srv/models"
	"user_srv/pkg"

	"user_srv/internal/svc"
	"user_srv/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type RealNameLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRealNameLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RealNameLogic {
	return &RealNameLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RealNameLogic) RealName(in *user.RealNameRequest) (*user.RealNameResponse, error) {
	var r models.RealName
	r.UserId = int(in.UserId)
	err := r.FindUserId()
	if err != nil {
		logx.Error("用户查询失败", err)
		return nil, err
	}
	if !pkg.RealNameAuth(in.IdCard, in.RealName) {
		logx.Error("用户实名失败")
		return nil, errors.New("用户实名失败")
	}
	if r.ID != 0 {
		logx.Error("用户已实名")
		return nil, errors.New("用户已实名")

	}
	r.RealName = in.RealName
	r.IdCard = in.IdCard
	err = r.RealNameCreate()
	if err != nil {
		logx.Error("保存用户信息失败", err)
		return nil, errors.New("保存用户信息失败")
	}

	return &user.RealNameResponse{
		RealName: int64(r.ID),
	}, nil
}
